package com.xiong.wuliao.mainfragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.xiong.wuliao.ColumnActivity;
import com.xiong.wuliao.PurchaseActivity;
import com.xiong.wuliao.R;
import com.xiong.wuliao.entity.Urls;
import com.xiong.wuliao.entity.ZhuanLan;
import com.xiong.wuliao.entity.ZhuanTi;
import com.xiong.wuliao.util.ZhuanLanJSON;
import com.xiong.wuliao.view.MyGridView;
import com.xiong.wuliao.view.MyPullToView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 第二个页面：分类Fragment页面
 */
public class CategoryFragment extends Fragment {
    private MyPullToView myPullToView; // 自定义组合控件
    private MyGridView myGridView;  // 自定义GridView
    private MyAdapter myAdapter; // 给GridView的自定义适配器

    private ImageView myImageViewCategory01; // 单品购买图片按钮
    private List<ZhuanLan> zhuanLanList = new ArrayList<>(); // 保存专栏部分服务器数据

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        findView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setGridView(); // 设置GridView属性
        initData();
        setMyAdapter();
        setListener();

    }

    /**
     * 设置GridView的属性
     */
    private void setGridView() {
        myPullToView.setGridViewNum(4); // 设置为4列
        myPullToView.setHorizontalSpacing(20); // 设置水平距离
        myPullToView.setVerticalSpacing(20); // 设置垂直距离
    }

    /**
     * 设置监听事件
     */
    private void setListener() {
        // 图片单品购买点击事件
        myImageViewCategory01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent0 = new Intent(getActivity(), PurchaseActivity.class);
                startActivity(intent0);
            }
        });

        // GridView的点击事件
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String string = zhuanLanList.get(position).getId();
                String name = zhuanLanList.get(position).getName();
                Intent intent = new Intent(getActivity(), ColumnActivity.class);
                intent.putExtra("storyId",string);
                intent.putExtra("storyName",name);
                startActivity(intent);
            }
        });

    }


    /**
     * 设置适配器
     */
    private void setMyAdapter() {
        myAdapter = new MyAdapter(getActivity());
        myGridView.setAdapter(myAdapter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getZhuanLanServer();

    }

    /**
     * 获取服务器专栏部分数据
     */
    private void getZhuanLanServer() {
        OkHttpUtils.get(Urls.ZhuanLanPath).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject jsonObject = new JSONObject(s.trim());
                    String result = jsonObject.optString("message");
                    if (result.equals("OK")){
                        zhuanLanList.addAll(ZhuanLanJSON.saveZhuanLanData(s.trim()));
                        myAdapter.notifyDataSetChanged();
                    }else {
                        Toast.makeText(getActivity(), "服务器开小差了哟", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void findView(View view) {
        myPullToView = (MyPullToView) view.findViewById(R.id.myPullToViewCategory);
        myGridView = (MyGridView) view.findViewById(R.id.myGridView);
        myImageViewCategory01 = (ImageView) view.findViewById(R.id.myImageViewCategory01);
    }

    /**
     * 下方专栏的适配器
     */
    private class MyAdapter extends BaseAdapter{
        Context context;
        LayoutInflater inflater;

        public MyAdapter(Context context) {
            this.context = context;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return zhuanLanList.size();
        }

        @Override
        public Object getItem(int position) {
            return zhuanLanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ZhuanLan zhuanLan = zhuanLanList.get(position);
            ViewHolder holder = null;
            if (convertView == null){
                convertView = inflater.inflate(R.layout.category_adapter_item,null);
                holder = new ViewHolder();

                holder.zhuanLanImageView = (ImageView) convertView.findViewById(R.id.zhuanLanImageView);
                holder.zhuanLanTextView = (TextView) convertView.findViewById(R.id.zhuanLanTextView);

                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            Picasso.with(context).load(zhuanLan.getIcon_url()).into(holder.zhuanLanImageView);
            holder.zhuanLanTextView.setText(zhuanLan.getName());

            return convertView;
        }
    }

    static class ViewHolder{
        public ImageView zhuanLanImageView; // 专栏的图片
        public TextView zhuanLanTextView; // 图片下的文字

    }

}
